<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
include_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'lib.json.service.class.php');

class LibJson {
	
	//encode
	function encode($value, $isHtml = false) {
		// Some versions of PHP have a broken json_encode, see PHP bug
		// 46944. Test encoding an affected character (U+20000) to
		// avoid this.
		if( !function_exists('json_encode') || $isHtml || strtolower(json_encode("\xf0\xa0\x80\x80")) != '\ud840\udc00' ) {
			$json = new Services_JSON();
			return $json->encode($value, $isHtml);
		} else {
			header('Content-type: application/json');
			return json_encode($value);
		}
	}
	
	//decode
	function decode($value, $assoc = false) {
		if( !function_exists('json_decode') ) {
			$json = new Services_JSON();
			$jsonDec = $json->decode($value);
			if( $assoc )
				$jsonDec = $this->_obj_to_array($jsonDec);
			return $jsonDec;
		} else {
			return json_decode($value, $assoc);
		}
	}
	
	//private
	function _obj_to_array($object, $recursive = true) {
		$array = array();
		foreach( get_object_vars($object) as $key => $value ) {
			if( is_object($value) && $recursive ) {
				$value = $this->_obj_to_array( $value );
			}
			
			$array[$key] = $value;
		}
		
		return $array;
	}
}

class JsonUtil {
	
	//encode
	function encode($value, $isHtml = false) {
		$obj = new LibJson();
		return $obj->encode($value, $isHtml);
	}
	
	//decode
	function decode($value, $assoc = false) {
		$obj = new LibJson();
		return $obj->decode($value, $assoc);
	}
}
//
?>